/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.user.web.stuteachers;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.thinkgem.jeesite.common.beanvalidator.BeanValidators;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.utils.excel.ImportExcel;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import com.thinkgem.jeesite.modules.user.entity.stuteachers.TpStudentTeacher;
import com.thinkgem.jeesite.modules.user.service.stuteachers.TpStudentTeacherService;

/**
 * 学生的辅导老师信息Controller
 * @author hhm
 * @version 2018-04-19
 */
@Controller
@RequestMapping(value = "${adminPath}/user/stuteachers/tpStudentTeacher")
public class TpStudentTeacherController extends BaseController {

	@Autowired
	private TpStudentTeacherService tpStudentTeacherService;
	@Autowired
	private SystemService systemService;
	
	@ModelAttribute
	public TpStudentTeacher get(@RequestParam(required=false) String id) {
		TpStudentTeacher entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = tpStudentTeacherService.get(id);
		}
		if (entity == null){
			entity = new TpStudentTeacher();
		}
		return entity;
	}
	
	/**
	 * @param tpStudentTeacher
	 * @param queryType 1=查询当前登录人作为教师的带教或者指导记录、2=查询当前人作为学员的记录
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("user:stuteachers:tpStudentTeacher:view")
	@RequestMapping(value = {"list", ""})
	public String list(TpStudentTeacher tpStudentTeacher,String queryType, HttpServletRequest request, HttpServletResponse response, Model model) {
		if("1".equals(queryType)){
			tpStudentTeacher.setTeacher(UserUtils.getUser());
		}else if("2".equals(queryType)){
			tpStudentTeacher.setStu(UserUtils.getUser());
		}else{//查询管辖部门下教师的带教或指导记录
			
		}
		Page<TpStudentTeacher> page = tpStudentTeacherService.findPage(new Page<TpStudentTeacher>(request, response), tpStudentTeacher); 
		model.addAttribute("page", page);
		return "modules/user/stuteachers/tpStudentTeacherList";
	}

	@RequiresPermissions("user:stuteachers:tpStudentTeacher:view")
	@RequestMapping(value = "form")
	public String form(TpStudentTeacher tpStudentTeacher, Model model) {
		model.addAttribute("tpStudentTeacher", tpStudentTeacher);
		return "modules/user/stuteachers/tpStudentTeacherForm";
	}

	@RequiresPermissions("user:stuteachers:tpStudentTeacher:edit")
	@RequestMapping(value = "save")
	public String save(TpStudentTeacher tpStudentTeacher, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, tpStudentTeacher)){
			return form(tpStudentTeacher, model);
		}
		tpStudentTeacherService.save(tpStudentTeacher);
		addMessage(redirectAttributes, "保存学生辅导老师成功");
		return "redirect:"+Global.getAdminPath()+"/user/stuteachers/tpStudentTeacher/?repage";
	}
	
	@RequiresPermissions("user:stuteachers:tpStudentTeacher:edit")
	@RequestMapping(value = "delete")
	public String delete(TpStudentTeacher tpStudentTeacher, RedirectAttributes redirectAttributes) {
		tpStudentTeacherService.delete(tpStudentTeacher);
		addMessage(redirectAttributes, "删除学生辅导老师成功");
		return "redirect:"+Global.getAdminPath()+"/user/stuteachers/tpStudentTeacher/?repage";
	}

	/**
	 * 下载导入数据模板
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("sys:stuteachers:tpStudentTeacher:view")
	@RequestMapping(value = "import/template")
	public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "教师指导学员数据导入模板.xlsx";
			List<TpStudentTeacher> list = Lists.newArrayList();
			TpStudentTeacher st=new TpStudentTeacher();
			list.add(st);
			new ExportExcel("教师指导学员数据", TpStudentTeacher.class, 2).setDataList(list).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/user/student/TpStudentTeacher/?repage";
	}

	/**
	 * 导入数据
	 * @param file
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("user:stuteachers:tpStudentTeacher:edit")
	@RequestMapping(value = "import", method= RequestMethod.POST)
	public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		if(Global.isDemoMode()){
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/user/student/TpStudentTeacher/?repage";
		}
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<TpStudentTeacher> list = ei.getDataList(TpStudentTeacher.class);
			systemService.setFieldId(list);
			for (TpStudentTeacher st : list){
				try{
					tpStudentTeacherService.save(st);
				}catch(ConstraintViolationException ex){
					failureMsg.append("<br/>"+st.toString()+" 导入失败：");
					List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
					for (String message : messageList){
						failureMsg.append(message+"; ");
						failureNum++;
					}
				}catch (Exception ex) {
					failureMsg.append("<br/> "+st.toString()+" 导入失败："+ex.getMessage());
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条，导入信息如下：");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/user/student/TpStudentTeacher/?repage";
	}
	/**
	 * 导出数据
	 * @param user
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("user:stuteachers:TpStudentTeacher:view")
	@RequestMapping(value = "export", method=RequestMethod.POST)
	public String exportFile(TpStudentTeacher TpStudentTeacher, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "教师指导学员数据"+ DateUtils.getDate("yyyy-MM-dd")+".xlsx";
			Page<TpStudentTeacher> page = tpStudentTeacherService.findPage(new Page<TpStudentTeacher>(request, response, -1), TpStudentTeacher);
			new ExportExcel("教师指导学员数据", TpStudentTeacher.class).setDataList(page.getList()).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/user/student/TpStudentTeacher/list?repage";
	}
}